<template>
  <div class="news">
    <el-button type="primary" @click="openDialog">新增新闻</el-button>

    <el-table :data="tableData" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="序号" width="180"></el-table-column>
      <el-table-column
        prop="title"
        label="新闻标题"
        width="180"
      ></el-table-column>
      <el-table-column prop="content" label="新闻图片">
        <template #default="scope">
          <div class="news-images">
            <img
              v-if="getFirstImage(scope.row.content)"
              :src="getFirstImage(scope.row.content)"
              alt
              style="
                width: 100%;
                height: auto;
                max-height: 100px;
                object-fit: cover;
              "
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="新闻内容">
        <template #default="scope">
          <div v-if="stripImages(scope.row.content).length > 100">
            <div
              v-html="stripImages(scope.row.content).slice(0, 100) + '...'"
            ></div>
          </div>
          <div v-else v-html="stripImages(scope.row.content)"></div>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="新闻类别">
        <template #default="scope">
          {{ scope.row.type === 1 ? "公司新闻" : "行业动态" }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            type="primary"
            @click="handleEdit(scope.$index, scope.row)"
          >
            <el-icon>
              <Edit />
            </el-icon>
          </el-button>
          <el-button
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >
            <el-icon>
              <Delete />
            </el-icon>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="新闻编辑" v-model="dialogFormVisible">
      <el-form :model="formData">
        <el-form-item label="新闻名称" :label-width="formLabelWidth">
          <el-input v-model="formData.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新闻内容" :label-width="formLabelWidth">
          <QuillEditorComponent
            ref="quillEditorRef"
            :content="formData.content"
            :uploadImg="uploadImg"
            :headers="headers"
            :imgServer="imgServer"
          />
        </el-form-item>
        <el-form-item label="新闻类别" :label-width="formLabelWidth">
          <el-radio v-model="formData.type" :label="1">公司新闻</el-radio>
          <el-radio v-model="formData.type" :label="2">行业动态</el-radio>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCreateOrModify"
          >确 定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Edit, Delete } from "@element-plus/icons-vue";
import QuillEditorComponent from "../../components/QuillEditorComponent.vue";

export default {
  name: "loginNews",
  components: {
    Edit,
    Delete,
    QuillEditorComponent,
  },
  data() {
    return {
      options: {},
      headers: {},
      tableData: [],
      formData: {
        id: 0,
        title: "",
        img: "",
        type: 1,
        content: "",
        createTime: new Date(),
      },
      dialogFormVisible: false,
      formLabelWidth: "120px",
      loading: true,
    };
  },
  mounted() {
    const token = `Browser ${sessionStorage.getItem("token")}`;
    this.options = {
      headers: {
        Authorization: token,
      },
    };
    this.headers = {
      Authorization: token,
    };
    this.loadData();
  },
  methods: {
    async loadData() {
      this.loading = true;
      try {
        const response = await this.$http.get("news/all", this.options);
        this.tableData = response.data;
      } catch (error) {
        this.$message.error(`网络或程序异常！${error.message}`);
      } finally {
        this.loading = false;
      }
    },
    openDialog() {
      if (this.formData.content !== "") {
        this.$refs.quillEditorRef.clearEditorContent();
      }
      this.formData = {
        id: 0,
        img: "",
        title: "",
        content: "",
        del: "",
        createTime: new Date(),
      };
      this.dialogFormVisible = true;
    },
    async handleCreateOrModify() {
      this.loading = true;
      try {
        if (!this.formData.id) {
          await this.$http.post("news/create", this.formData, this.options);
          this.$message.success("创建成功！");
        } else {
          await this.$http.put("news/update", this.formData, this.options);
          this.$message.success("修改成功！");
        }
        this.dialogFormVisible = false;
        await this.loadData();
      } catch (error) {
        this.$message.error(`网络或程序异常！${error.message}`);
      } finally {
        this.loading = false;
      }
    },
    handleEdit(index, row) {
      this.formData = { ...row };
      this.dialogFormVisible = true;
    },
    async handleDelete(index, row) {
      try {
        await this.$messageBox.confirm(
          "此操作将永久删除该文件, 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );
        this.loading = true;
        await this.$http.delete(`news/delete/${row.id}`, this.options);
        this.$message.success("删除成功！");
        await this.loadData();
      } catch (error) {
        if (error.name === "CancelError") {
          this.$message.info("已取消删除");
        } else {
          this.$message.error(`网络或程序异常！${error.message}`);
        }
      } finally {
        this.loading = false;
      }
    },
    stripImages(html) {
      return html.replace(/<img[^>]*>/g, "");
    },
    getFirstImage(html) {
      const imgRegex = /<img[^>]+src="([^">]+)"/;
      const match = html.match(imgRegex);
      return match ? match[1] : "";
    },
  },
};
</script>

<style lang="scss" scoped>
.el-table {
  margin-top: 20px;
}

.avatar {
  width: 300px;
}

.quill-editor-wrapper {
  min-height: 200px;
}

.hidden-upload {
  display: none;
}

.news-images {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}
</style>
